package win.bigwhale.defense;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Monster extends JPanel {
	private MonsterPath path;
	private Timer timer;
	private Point monsterPosition;
	private Map map;
	public Monster(Map map) {
		this.setLayout(null);
		this.setSize(48, 48);
		this.path = new MonsterPath(map.getMonsterPath());
		this.monsterPosition = new Point(path.initPosition());
		this.map = map;

		timer = new Timer(500, new MoveNextListener());
		timer.start();
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		this.setLocationByMonsterPosition(monsterPosition);
		g.setColor(Color.RED);
		g.fillRect(0, 0, 48, 48);
	}

	/**
	 * if the next position is still in the map, monster move to the next position.
	 * 
	 * if the current position is the last one, the monster just disappears.
	 */
	private void MoveNextListener() {
		Point nextPosition = path.moveNext();
		if (nextPosition != null) {
			monsterPosition.x = nextPosition.x;
			monsterPosition.y = nextPosition.y;
			repaint();
		} else {
			this.setVisible(false);
			map.remove(this);
		}
	}

	/**
	 * according to position, get the real location of the monster at map.
	 * 
	 * @param position
	 */
	private void setLocationByMonsterPosition(Point position) {
		int locationX = 2 + position.x * 50;
		int locationY = 2 + position.y * 50;
		this.setLocation(locationX, locationY);
	}

	public class MoveNextListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			MoveNextListener();
		}
	}
}
